package com.tools.scanner.utils

import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.CalendarContract
import android.provider.ContactsContract
import android.provider.Settings
import android.widget.Toast
import com.google.mlkit.vision.barcode.common.Barcode
import com.tools.scanner.QrApp
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

fun String.openSearch() {
    val intent = Intent(Intent.ACTION_WEB_SEARCH)
    intent.putExtra(SearchManager.QUERY, this)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    try {
        QrApp.app.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun String.copyText() {
    val context = QrApp.app
    val clipboardManager =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText("label", this)
    clipboardManager.setPrimaryClip(clipData)
}

fun Int.showToast() {
    ActivityStack.popActivity()?.let {
        Toast.makeText(it, this, Toast.LENGTH_SHORT).show()
    }
}

fun String.showToast() {
    ActivityStack.popActivity()?.let {
        Toast.makeText(it, this, Toast.LENGTH_SHORT).show()
    }
}

fun String.shareText() {
    val intent = Intent(Intent.ACTION_SEND)
    intent.setType("text/plain");
    intent.putExtra(
        "android.intent.extra.TEXT",
        this
    )
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    try {
        QrApp.app.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

@SuppressLint("NewApi")
fun Barcode.WiFi.connectionWifi() {
    val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    QrApp.app.startActivity(intent)
}

fun Barcode.ContactInfo.saveContact() {
    val phones = phones
    val contentValuesData = ArrayList<ContentValues>()

    if (phones.isNotEmpty()) {
        phones.forEach { phone ->
            val values = ContentValues().apply {
                put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone.number ?: "")
                put(
                    ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                )

                // 根据电话号码类型设置类型
                when (phone.type) {
                    Barcode.Phone.TYPE_MOBILE -> {
                        put(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
                        )
                    }

                    Barcode.Phone.TYPE_WORK -> {
                        put(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_WORK
                        )
                    }

                    Barcode.Phone.TYPE_HOME -> {
                        put(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_HOME
                        )
                    }

                    Barcode.Phone.TYPE_FAX -> {
                        put(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX
                        )
                    }

                    else -> put(
                        ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_OTHER
                    ) // 默认类型
                }
            }
            contentValuesData.add(values)
        }
    }

    val addresses = addresses
    if (addresses.isNotEmpty()) {
        addresses.forEach { address ->
            val homeAddr = ContentValues()
            homeAddr.put(
                ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE
            )

            homeAddr.put(
                ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                address.addressLines.joinToString("\n")
            )

            when (address.type) {
                Barcode.Address.TYPE_HOME -> {
                    homeAddr.put(
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME
                    )
                }

                Barcode.Address.TYPE_WORK -> {
                    homeAddr.put(
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK
                    )
                }

                else -> {
                    homeAddr.put(
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER
                    )
                }
            }

            contentValuesData.add(homeAddr)
        }
    }


    val emails = emails
    if (emails.isNotEmpty()) {
        emails.forEach { email ->
            val values = ContentValues()
            values.put(
                ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
            )
            values.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email.address ?: "")
            when (email.type) {
                Barcode.Email.TYPE_WORK -> {
                    values.put(
                        ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_WORK
                    )
                }

                Barcode.Email.TYPE_HOME -> {
                    values.put(
                        ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_HOME
                    )
                }

                else -> {
                    values.put(
                        ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_OTHER
                    )
                }
            }
            contentValuesData.add(values)
        }
    }

    val intent = Intent(ContactsContract.Intents.Insert.ACTION).apply {
        type = ContactsContract.Contacts.CONTENT_TYPE
        putExtra(
            ContactsContract.Intents.Insert.NAME,
            name?.formattedName
        )
        putExtra(
            ContactsContract.Intents.Insert.COMPANY,
            organization
        )
        putParcelableArrayListExtra(
            ContactsContract.Intents.Insert.DATA,
            contentValuesData
        )
        putExtra(
            ContactsContract.Intents.Insert.NOTES,
            title
        )
    }

    intent.apply {
        flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK
    }

    try {
        QrApp.app.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun String.openBrowser() {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.setData(Uri.parse(this))
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    try {
        QrApp.app.startActivity(intent);
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Barcode.Sms.sendSms() {
    val intent = Intent(Intent.ACTION_SENDTO)
    intent.setData(Uri.parse("smsto:$phoneNumber"))
    intent.putExtra("sms_body", message)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    try {
        QrApp.app.startActivity(intent);
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Barcode.Email.sendEmail() {
    val mailtoUri = Uri.parse("mailto:${Uri.encode(address)}").buildUpon()
        .build()

    val emailIntent = Intent(Intent.ACTION_SENDTO, mailtoUri).apply {
        putExtra(Intent.EXTRA_SUBJECT, subject)
        putExtra(Intent.EXTRA_TEXT, body)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }

    try {
        QrApp.app.startActivity(emailIntent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Barcode.CalendarEvent.saveCalendar() {
    val intent = Intent(Intent.ACTION_INSERT).apply {
        data = CalendarContract.Events.CONTENT_URI
        putExtra(CalendarContract.Events.TITLE, summary)
        putExtra(CalendarContract.Events.DESCRIPTION, description)
        putExtra(CalendarContract.Events.EVENT_LOCATION, location)
        putExtra(CalendarContract.Events.ORGANIZER, organizer)
        putExtra(CalendarContract.Events.STATUS, status)
        putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start?.toMillis())
        putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end?.toMillis())
        putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY)
    }

    intent.apply {
        flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK
    }
    try {
        QrApp.app.startActivity(intent);
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Barcode.CalendarDateTime.toMillis(): Long {
    val calendar = Calendar.getInstance()
    calendar.set(year, month - 1, day, hours, minutes, seconds)
    return calendar.timeInMillis
}

fun Barcode.GeoPoint.search() {
    val latitude = lat
    val longitude = lng

    val gmmIntentUri = Uri.parse(
        "geo:" + latitude + "," + longitude
                + "?q=" + latitude + "," + longitude
    )

    val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
    mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    try {
        QrApp.app.startActivity(mapIntent);
    } catch (e: Exception) {
        val webUri = Uri.parse(
            "https://www.google.com/maps/search/?api=1&query="
                    + latitude + "," + longitude
        )
        val webIntent = Intent(Intent.ACTION_VIEW, webUri)
        try {
            QrApp.app.startActivity(webIntent)
        } catch (e: Exception) {

        }
    }
}

fun Barcode.Phone.callPhone() {
    val phoneUri = "tel:${number}"
    val intent = Intent(Intent.ACTION_DIAL, Uri.parse(phoneUri))
    intent.apply {
        flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK
    }
    try {
        QrApp.app.startActivity(intent);
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun Long.formatTimestamp(): String {
    val date = Date(this)
    val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
    return format.format(date)
}